<template>
    <div>
        <div class="search-container">
            <el-form :inline="true" :model="formSearch" class="demo-form-inline">
                <el-form-item>
                    <el-input v-model="formSearch.name" placeholder="标题" size="small" autocomplete="on" clearable>
                    </el-input>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="onSearch" size="small">查询</el-button>
                </el-form-item>
            </el-form>
        </div>

        <div class="toolbar">
            <el-button type="text" icon="el-icon-plus" :underline="false" @click="openFormDialog(null)">创建</el-button>
        </div>

        <el-table border :data="pageData" style="width: 100%"
            :default-sort="{ prop: 'createTime', order: 'descending' }" @sort-change="handlerSort">
            <el-table-column type="selection" width="55" />
            <el-table-column type="index" width="50" label="序号" />
            <el-table-column prop="name" label="标题" sortable width="180" />
            <el-table-column prop="className" label="所属分类" sortable />
            <el-table-column prop="note" label="简要说明" />
            <el-table-column prop="createTime" label="创建时间" sortable width="120" :formatter="formatterDate" />

            <el-table-column label="操作" width="150">
                <template slot-scope="scope">
                    <el-button size="mini" @click="openFormDialog(scope.row)">编辑</el-button>
                    <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <div class="pagination">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="formSearch.pageIndex" :page-size="formSearch.pageSize"
                layout="total, sizes, prev, pager, next, jumper" :total="totalCount">
            </el-pagination>
        </div>

        <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" :before-close="closeFormDialog">
            <el-form :model="formData" :rules="rules" ref="dialogForm">

                <el-form-item label="所属分类" :label-width="labelwidth" prop="classId">
                    <treeselect v-model="formData.classId" :multiple="false" :isLeaf="true" :flat="true"
                        :options="treeData" :normalizer="normalizer" placeholder="请选择分类" :showCount="true"
                        :disabled="isEdit">
                        <div slot="value-label" slot-scope="{node}">{{ node.label }}</div>
                    </treeselect>
                </el-form-item>


                <el-form-item label="标题" :label-width="labelwidth" prop="name">
                    <el-input v-model="formData.name" autocomplete="off" clearable></el-input>
                </el-form-item>

                <el-form-item label="简要说明" :label-width="labelwidth" prop="note">
                    <el-input v-model="formData.note" autocomplete="off" clearable></el-input>
                </el-form-item>

                <el-form-item label="参考站点" :label-width="labelwidth" prop="url">
                    <el-input v-model="formData.url" autocomplete="off" clearable></el-input>
                </el-form-item>

                <el-form-item label="详细说明" :label-width="labelwidth" prop="detailed">
                    <ckeditor class="ckeditor" v-model="formData.detailed"></ckeditor>
                </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="closeFormDialog">取 消</el-button>
                <el-button type="primary" @click="saveForm">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import api from '../../../api/admin/articlesApi.js'
import apiClass from '../../../api/admin/articleclassesApi.js'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'


import CKEditor from "ckeditor4-vue";

export default ({
    name: 'articles',
    components: {
        Treeselect,
        'ckeditor': CKEditor.component
    },
    data() {
        return {
            formSearch: {
                username: '',
                name: '',
                pageIndex: 0,
                pageSize: 10,
                obderby: ''
            },
            normalizer(node) {
                return {
                    id: node.id,
                    label: node.name,
                    children: node.children.length > 0 ? node.children : null,
                    isDefaultExpanded: node.id === '0',
                    isDisabled: node.id === '0'
                }
            },
            treeData: [],
            totalCount: 0,
            pageData: [],
            formData: {},
            dialogTitle: '用户',
            dialogFormVisible: false,
            labelwidth: '100px',
            defaultProps: {
                /** 唯一标识 **/
                value: 'id',
                /** 标签显示 **/
                label: 'name',
                cacheOptions: false,
                /** 子级 **/
                children: "children",
                /** 是否禁用 **/
                disabled: function (data, node) {
                    if (data.isLeaf == 1) {
                        return false;
                    } else {
                        return true;
                    }
                }
            },
            categoryId: null,
            categoryOptions: [],
            rules: {
                name: [
                    { required: true, message: "请输入标题", trigger: "blur" }
                ]
            }
        }
    },
    methods: {
        //节点点击事件
        handleNodeClick(data, node, nodeData) {
            this.mineStatusValue = data.id;
            this.mineStatus = data.name;
            // 选择器执行完成后，使其失去焦点隐藏下拉框的效果
            this.$refs.treeSelect.blur();
        },
        handleSizeChange(val) {
            this.formSearch.pageSize = val
            this.onSearch()
        },
        handleCurrentChange(val) {
            this.formSearch.pageIndex = val - 1
            this.onSearch()
        },
        handlerSort(column) {
            if (column.order) {
                this.formSearch.obderby = column.prop + ' ' + column.order
            } else {
                this.formSearch.obderby = ''
            }
            this.onSearch()
        },
        formatterDate(row) {
            return this.$dayjs(row.value).format('YYYY-MM-DD')
        },
        //删除单行记录
        handleDelete(row) {
            this.$confirm('确定删除当前记录', '删除提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                api.Delete(row.id).then(res => {
                    this.$message({ message: '删除成功', type: 'success' })
                    this.onSearch()
                })
            }).catch(() => {
                return
            });
        },
        //打开创建编辑窗口
        openFormDialog(row) {
            if (row !== null) {
                console.log(row)
                this.formData = Object.assign({}, row)
                console.log(Object.assign({}, row))
                this.formData.password = ''
            }

            if (this.isEdit) {
                this.dialogTitle = '编辑用户'
            } else {
                this.dialogTitle = '创建用户'
            }
            this.dialogFormVisible = true
        },
        //关闭创建编辑窗口
        closeFormDialog() {
            this.$refs.dialogForm.resetFields()
            this.formData = {}
            this.dialogFormVisible = false
        },
        //保存创建及编辑
        saveForm() {
            this.$refs.dialogForm.validate((valid) => {
                if (valid) {
                    if (this.isEdit) {
                        api.Update(this.formData).then(res => {
                            this.$message({ message: '操作成功', type: 'success' })
                            this.onSearch()
                            this.closeFormDialog()
                        })
                    } else {
                        api.Create(this.formData).then(res => {
                            this.$message({ message: '操作成功', type: 'success' })
                            this.onSearch()
                            this.closeFormDialog()
                        })
                    }

                }
            });
        },
        //搜索
        onSearch() {
            api.getPage(this.formSearch, null).then(res => {
                this.pageData = res.data.data.dataArray
                this.totalCount = res.data.data.totalCount
                this.formSearch.pageIndex = res.data.data.pageIndex
                this.formSearch.pageSize = res.data.data.pageSize
            });
        },
        getClassTree() {
            apiClass.getTree("0").then(res => {
                this.treeData = res.data.data
            });
        },
        // 事件 onNamespaceLoaded
        onNamespaceLoaded(CKEDITOR) {
            console.log("CKEDITOR", CKEDITOR);
        }
    },
    computed: {
        isEdit() {
            return this.formData.id != undefined
        }
    },
    mounted() {
        this.onSearch();
        this.getClassTree();
    }
})
</script>
<style lang="less" scoped>
.labelClassName {
    padding-left: -2em;
}
</style>